<html>
<head>
  <script src="../dist/incremental-dom.js"></script>
</head>
<body>
  <div id="container"></div>

  <script type="module">
    import {before} from './demo_utils.js';

    const {
      patch,
      elementOpen,
      elementVoid,
      elementClose,
      text,
    } = IncrementalDOM;

    const container = document.getElementById('container');

    function update(data) {
      patch(container, function() {
        elementOpen('div');
          elementVoid('input', null, null,
              'type', 'text',
              'oninput', handleInput);
        elementClose('div');
        elementOpen('div');
          text('last 10 inputs');
        elementClose('div');

        elementOpen('div');
          lastInputs.forEach(function(item) {
            // The key for this item is the item's id. During each update, DOM
            // nodes are reused based on the key. This causes an additional
            // div and text node to be created rather than all the text nodes
            // being updated.
            elementOpen('div', item.id, null,
                'style', 'min-height: 1em');
              text(item.text);
            elementClose('div');
          });
        elementClose('div');

        elementOpen('div', null, null,
            'style', 'position: absolute; top: 0; right: 0;');
          text('text nodes created: ' + data.textNodesCreated);
        elementClose('div');
      });
    }

    let lastInputs = [];
    let textNodesCreated = 0;

    before(document, 'createTextNode', function() {
      textNodesCreated += 1;
    });

    function handleInput(e) {
      lastInputs = [{
          text: e.target.value,
          id: Date.now()
        }]
        .concat(lastInputs)
        .slice(0, 10);

      update({
        lastInputs,
        textNodesCreated,
      });
    }

    // Initial render
    update({
      lastInputs,
      textNodesCreated,
    });
  </script>
</body>
</html>
